<template>
  <el-row
    class="directory-row"
    type="flex"
    align="middle"
    justify="space-between"
    v-if="!$util.isEmpty(item)"
    @click.native="onStartLearning(item)"
  >
    <el-row type="flex" align="middle" class="left">
      <template v-if="item.course_type == 1">
        <template v-if="!$util.isEmpty(item.section_data)">
          <el-tag class="type" effect="dark" size="mini">{{
            item.section_data.data_type_text
          }}</el-tag>
        </template>
      </template>
      <div class="name col-left">{{ item.title }}</div>
      <template v-if="item.is_buy == 0">
        <span class="price col-left" v-if="item.price > 0">{{ item.price | formatMoney }}</span>
        <el-tag type="success col-left" effect="dark" size="mini" v-if="item.audition > 0"
          >可试看</el-tag
        >
      </template>
    </el-row>
    <el-row type="flex" align="middle" class="right">
      <i
        class="lock col-left edu-icon-suo"
        v-if="
          item.course_type == 1 &&
            item.course_lock == 1 &&
            item.lock == 1 &&
            !getSectionPlayLock.includes(item.id)
        "
      ></i>
      <!-- 未购买课时 -->
      <template v-if="item.is_buy == 0">
        <!-- 直播状态 -->
        <template v-if="!$util.isEmpty(item.live_rate)">
          <div class="live-time">
            {{ getFormateDate(item.start_time) }} -
            {{ item.end_time | parseTime('{h}:{i}') }}
          </div>
          <!-- <div class="live-status">
            {{ item.live_rate.status_text }}
          </div> -->
        </template>
        <!-- 可试看 -->
        <el-button
          v-if="item.audition > 0"
          class="btn col-left"
          type="primary"
          size="small"
          round
          @click.stop="seeToPath(item)"
          >试看</el-button
        >
        <!-- 价格大于0可购买 -->
        <el-button
          v-if="parseFloat(item.price) > 0"
          class="btn col-left"
          type="danger"
          size="small"
          round
          plain
          @click.stop="handleSectionBuy(item.id)"
          >立即购买</el-button
        >
      </template>
      <!-- 课时购买状态 -->
      <template v-else>
        <!-- 课件下载 -->
        <template v-if="!$util.isEmpty(item.material_data)">
          <el-button
            class="download col-left"
            type="text"
            icon="edu-icon-xiazai"
            v-down="item.material_data.fileurl"
          ></el-button>
        </template>
        <!-- 点播课程进度 -->
        <template v-if="!$util.isEmpty(item.section_rate)">
          <template v-if="item.section_rate.status == 999">
            <!-- 音视频已学习时长 -->
            <template v-if="!$util.isEmpty(item.section_data)">
              <div
                class="time col-left"
                v-if="item.section_data.data_type == 1 || item.section_data.data_type == 2"
              >
                <i class="edu-icon-historyrecord edu-icon--left"></i>学习至{{
                  item.section_rate.current_time | formatSeconds
                }}
              </div>
            </template>
          </template>
          <!-- 已完成 -->
          <div class="success col-left" v-else-if="item.section_rate.status == 992">
            <i class="el-icon-success"></i>
            {{ item.section_rate.status_text }}
          </div>
          <el-button
            class="btn col-left"
            type="primary"
            size="small"
            round
            @click.stop="videoToPath(item)"
            >{{ statusText[item.section_rate.status] }}</el-button
          >
        </template>
        <!-- 直播课程进度 -->
        <template v-if="!$util.isEmpty(item.live_rate)">
          <!-- 未开始 -->
          <template v-if="item.live_rate.status == 957">
            <div class="live-time">
              {{ getFormateDate(item.start_time) }} -
              {{ item.end_time | parseTime('{h}:{i}') }}
            </div>
            <div class="live-status">
              {{ item.live_rate.status_text }}
            </div>
          </template>
          <!-- 直播中 -->
          <template v-if="item.live_rate.status == 999">
            <el-button
              class="col-left"
              type="primary"
              size="small"
              @click.stop="liveToPath(item)"
              round
            >
              <div class="playing-btn">
                <div class="playing">
                  <div class="playing__bar playing__bar1"></div>
                  <div class="playing__bar playing__bar2"></div>
                  <div class="playing__bar playing__bar3"></div>
                  <div class="playing__bar playing__bar4"></div>
                </div>
                <span>{{ item.live_rate.status_text }}</span>
              </div>
            </el-button>
          </template>
          <!-- 已结束 -->
          <template v-if="item.live_rate.status == 992">
            <!-- 声网 -->
            <template v-if="item.live_provider === 2">
              <el-button
                class="live-btn"
                round
                size="small"
                v-if="!$util.isEmpty(item.live_rate.callback_url)"
                @click.stop="handleLiveCallback(item)"
                >观看回放</el-button
              >
              <div class="live-status" v-else>无回放</div>
            </template>
            <!-- cc直播 -->
            <template v-else-if="item.live_provider === 3">
              <el-button
                class="live-btn"
                round
                size="small"
                v-if="
                  !$util.isEmpty(item.live_rate.cc_replay_id) ||
                    !$util.isEmpty(item.live_rate.cc_replay_url)
                "
                @click.stop="handleLiveCallback(item)"
                >观看回放</el-button
              >
              <div class="live-status" v-else>无回放</div>
            </template>
          </template>
        </template>
      </template>
    </el-row>

    <!-- 人脸验证 -->
    <EduFaceVerify
      v-if="faceVisible"
      :visible.sync="faceVisible"
      scene_key="course_section"
      :scene_id="faceData.id || 0"
      scene_type="1"
      @cancel="handleFace"
    ></EduFaceVerify>
  </el-row>
</template>

<script>
// eslint-disable-next-line no-undef
Vue.directive('down', {
  inserted: (el, binding) => {
    el.style.cssText = 'cursor: pointer;color:write;'
    el.addEventListener('click', () => {
      let link = document.createElement('a')
      let url = binding.value
      fetch(url)
        .then(res => res.blob())
        .then(blob => {
          // 将链接地址字符内容转变成blob地址
          link.href = URL.createObjectURL(blob)
          link.download = ''
          document.body.appendChild(link)
          link.click()
        })
    })
  }
})
import eventVue from '../watch/sectiobWatchEventVue.js'
import Base64 from '@/utils/base64.js'
import { parseTime } from '@/utils/filters.js'
import EduFaceVerify from '@/components/EduFaceVerify'
import { mapState, mapGetters } from 'vuex'
export default {
  props: {
    item: {
      type: Object,
      default: () => {}
    },
    classId: {
      type: Number,
      default: 0
    },
    detailInfo: {
      type: Object,
      default: () => {}
    }
  },
  components: {
    EduFaceVerify
  },
  data() {
    return {
      statusText: { 957: '开始学习', 999: '继续学习', 992: '继续学习' },
      faceVisible: false,
      faceData: null
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.info,
      token: state => state.user.token,
      getSectionPlayLock: state => state.course.currentSectionPlayLock
    }),
    ...mapGetters({
      faceStatus: 'projectSetting/getGlobFaceStatus'
    })
  },
  methods: {
    // 试看
    seeToPath(item) {
      if (this.detailInfo.look_need_login == 1) {
        this.$globalToLogin(() => {
          this.$store.commit('course/setCurrentPlayItem', {
            ...item
          })
          eventVue.$emit('sendSectionBybus')
          this.toPathSection(`watch`, item.id)
        })
      } else {
        this.$store.commit('course/setCurrentPlayItem', {
          ...item
        })
        eventVue.$emit('sendSectionBybus')
        this.toPathSection(`watch`, item.id)
      }
    },
    // 课时跳转
    toPathSection(url, id) {
      this.$router.push({
        path: `/course/${this.$route.params.id}/${url}`,
        query: {
          mid: id
        }
      })
    },
    // 开始学习
    async videoToPath(item) {
      let pick = () => {
        // 是否需要人脸识别
        eventVue.$emit('faceEntranceBybus')
        if (this.detailInfo.onhook_type == 3) {
          this.faceData = item
          this.faceEntrance()
        } else {
          this.jump(item)
        }
      }
      // 点播解锁模式
      if (item.course_type == 1 && item.course_lock == 1 && item.lock == 1) {
        let lock = await this.$api.getCourseUnlock(
          {
            course_id: item.course_id,
            section_id: item.id,
            class_id: this.classId
          },
          res => {
            return res.data
          },
          _ => {
            return false
          }
        )
        if (!lock) {
          this.$message.info('课时未解锁')
          return
        }
      }
      pick()
    },
    jump(item) {
      this.$store.commit('course/setCurrentPlayItem', {
        ...item,
        audition: 0
      })
      // 音视频
      this.toPathSection(`watch`, item.id)
      eventVue.$emit('sendSectionBybus')
    },
    handleFace() {
      this.jump(this.faceData)
    },
    // 谢谢
    onStartLearning(item) {
      // 已购买
      if (item.is_buy == 1) {
        // 点播
        if (!this.$util.isEmpty(item.section_rate)) {
          this.videoToPath(item)
        }
        // 直播
        if (!this.$util.isEmpty(item.live_rate)) {
          if (item.live_rate.status == 957) {
            // 未开始
            this.$message.info('直播未开始')
          } else if (item.live_rate.status == 999) {
            // 直播中
            this.liveToPath(item)
          } else if (item.live_rate.status == 992) {
            // 已结束
            if (this.$util.isEmpty(item.live_rate.cc_replay_id)) {
              this.$message.info('无回放')
            } else {
              // cc回放
              this.handleLiveCallback(item)
            }
          }
        }
      } else {
        if (item.audition > 0) {
          // 试看
          this.seeToPath(item)
        } else if (item.price > 0) {
          // 课程购买
          this.handleSectionBuy(item.id)
        } else {
          // 免费课时
          this.$message.info('请先将课程加入学习')
        }
      }
    },
    // 窗口
    faceEntrance() {
      // 已认证
      if (this.faceStatus) {
        this.$messageBox
          .confirm('请进行人脸验证', {
            type: 'none',
            center: true,
            confirmButtonText: '去验证'
          })
          .then(() => {
            this.faceVisible = true
          })
          .catch(() => {})
      } else {
        this.$messageBox
          .confirm('未完成人脸认证，请先去认证', {
            type: 'none',
            center: true,
            confirmButtonText: '去认证'
          })
          .then(() => {
            this.$router.push({
              path: '/my/profile/face_verify',
              query: {
                back: 1
              }
            })
          })
          .catch(() => {})
      }
    },
    // 进入直播
    liveToPath(item) {
      this.$store.commit('course/setCurrentPlayItem', {
        ...item
      })
      if (item.live_provider === 2) {
        // 声网直播
        this.$api.getLiveAgoraRoomInfo(item.id, res => {
          const {
            data: { info }
          } = res
          let agoraName = {
            1: 'agora-big-class',
            2: 'agora-small-class',
            3: 'agora-one-to-one'
          }
          let agoraRoom = agoraName[info.course_live_type]
          this.$router.push({
            name: agoraRoom
          })
        })
      } else if (item.live_provider === 3) {
        // cc直播
        if (item.section_live.live_type === 2) {
          // 大班课
          this.$router.push({
            name: 'cc-big-class'
          })
        } else if (item.section_live.live_type === 3) {
          // 小班课
          const ccLive = item.section_live
          const user = this.userInfo
          const token = this.token
          const params = {
            userid: ccLive.cc_userid,
            roomid: ccLive.cc_room_id,
            password: ccLive.authtype === 0 ? `${token.ak}:${token.sk}` : '',
            username: user.nick_name,
            autoLogin: true,
            role: 'talker',
            template: 32
          }
          const url = `https://class.csslcloud.net/hdclass/#/talker?${this.params(params)}`
          this.$router.push({
            name: 'cc-live',
            query: {
              view: Base64.encode(url)
            }
          })
        }
      }
    },
    params(obj) {
      let result = ''
      let item
      for (item in obj) {
        if (obj[item] && String(obj[item])) {
          result += `&${item}=${obj[item]}`
        }
      }
      if (result) {
        result = result.slice(1)
      }
      return result
    },
    // 直播回放
    handleLiveCallback(item) {
      this.$store.commit('course/setCurrentPlayItem', {
        ...item
      })
      if (item.live_provider === 2) {
        // 声网
        this.toPathSection(`watch`)
      } else if (item.live_provider === 3) {
        // cc直播
        if (item.section_live.live_type === 2) {
          // 大班课
          this.$router.push({
            name: 'cc-replay-big'
          })
        } else if (item.section_live.live_type === 3) {
          // 小班课
          let ccLive = item.section_live
          let user = this.userInfo
          let token = this.token
          let params = {
            viewertoken: ccLive.authtype === 0 ? `${token.ak}:${token.sk}` : '',
            viewername: user.nick_name,
            autoLogin: true
          }
          let url = `${ccLive.cc_replay_url}&viewertoken=${params.viewertoken}&viewername=${params.viewername}&autoLogin=${params.autoLogin}`
          this.$router.push({
            name: 'cc-live',
            query: {
              view: Base64.encode(url)
            }
          })
        }
      }
    },
    // 课时购买
    handleSectionBuy(id) {
      this.$router.push({
        path: '/buy/section',
        query: {
          sid: id,
          redirect: this.$route.path
        }
      })
    },
    getFormateDate(timestamp) {
      const format = '{y}-{m}-{d}'
      let now = new Date() // 当前
      if (timestamp.toString().length == 10) timestamp *= 1000
      let date = new Date(timestamp)
      const nextDate = function(date, amount = 1) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount)
      }
      // 当前年
      if (now.getFullYear() == date.getFullYear()) {
        if (parseTime(now, format) == parseTime(date, format)) {
          return parseTime(timestamp, '今天 {h}:{i}')
        } else if (parseTime(nextDate(now), format) == parseTime(date, format)) {
          return parseTime(timestamp, '明天 {h}:{i}')
        } else {
          return parseTime(timestamp, '{m}月{d}日 {h}:{i}')
        }
      } else {
        return parseTime(timestamp, '{y}年{m}月{d}日 {h}:{i}')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.directory-row {
  padding-left: 15px;
  height: 51px;
  cursor: pointer;
  border-bottom: 1px solid $border-color-divider;
  transition: all 0.1s;
  .btn {
    display: none;
  }
  .col-left {
    margin-left: 10px;
  }
  .download {
    font-size: 16px;
  }
  .type {
    color: #6e6e6e;
    background-color: #f1f1f1;
    border-color: #f1f1f1;
    transition: all 0.1s;
  }
  .name {
    font-size: 14px;
    font-weight: 400;
    color: $text-color-secondary;
    max-width: 290px;
    @include ellipsis();
  }
  .lock {
    color: #dcdfe6;
    font-size: 16px;
  }
  .price {
    font-size: 14px;
    color: $text-color-price;
  }
  .time {
    font-size: 14px;
    font-weight: 400;
    color: $text-color-auxiliary;
    .edu-icon-historyrecord {
      @include edu-color-auxiliary;
    }
  }
  .success {
    color: $text-color-auxiliary;
    font-size: 14px;
    .el-icon-success {
      color: $text-color-free;
    }
  }
  .live-time {
    font-size: 13px;
    color: $text-color-auxiliary;
  }
  .live-status {
    font-size: 13px;
    color: $text-color-auxiliary;
    padding: 9px 15px;
  }
  .playing-btn {
    display: flex;
    align-items: center;
  }
  .playing {
    flex: 0 0 12px;
    width: 12px;
    height: 9px;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-right: 5px;
  }
  .playing__bar {
    width: 2.2px;
    height: 100%;
    background: #fff;
    animation: up-and-down 1.3s ease infinite alternate;
  }
  .playing__bar1 {
    height: 60%;
  }
  .playing__bar2 {
    height: 30%;
    animation-delay: -2.4s;
  }
  .playing__bar3 {
    height: 75%;
    animation-delay: -3.7s;
  }
  .playing__bar4 {
    height: 45%;
    animation-delay: -4.8s;
  }
  &:hover {
    background-color: #eef4ff;
    .btn {
      display: block;
    }
    .type {
      color: #ffffff;
      @include edu-color-primary(background-color);
      @include edu-color-primary(border-color);
    }
  }
}

@keyframes up-and-down {
  10% {
    height: 30%;
  }
  30% {
    height: 100%;
  }
  60% {
    height: 50%;
  }
  80% {
    height: 75%;
  }
  100% {
    height: 20%;
  }
}
</style>
